﻿/******************************************************   
创建者: 梁家健
创建时间: 2017-03-20
修改:
修改时间: 
功能: 企划设置
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.library;
using com.nm.library.Helper;
using george.Data;
using NHibernateVertica;
using PlanAPI.model;

namespace PlanAPI
{
    [Description("企划设置")]
    public class PLPlanYMSetHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        /// Writer：梁家健
        /// Create Date：2017-03-20
        [MustLogin]
        [Description("企划设置列表")]
        [ReturnType(typeof(IList<PLPlanYMSetModel.NeceModel>))]
        public ApiResult GetPLPlanYMSetList()
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                //var count = ReturnPLPlanYMSetCount();
                //var result = PaperData<PLPlanYMSetModel.ListModel>.Create(count, Size, Page);
                var dt = ReturnPLPlanYMSetList();
                var list = ModelConvertHelper<PLPlanYMSetModel.ListModel>.ConvertToModel(dt);
                return Success(list);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        ///// <summary>
        ///// 返回企划设置总条数
        ///// </summary>
        ///// <returns></returns>
        ///// Writer：梁家健
        ///// Create Date：2017-03-20
        //public int ReturnPLPlanYMSetCount()
        //{
        //    try
        //    {
        //        var sql = @"select count(*) from goods.goods_PL_PlanYMSet";
        //        var cmd = Helper.GetSqlStringCommand(sql);
        //        return Convert.ToInt32(Helper.ExecuteScalar(cmd));
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        /// <summary>
        /// 返回企划设置
        /// </summary>
        /// <param name="Page"></param>
        /// <param name="Size"></param>
        /// <returns></returns>
        /// Writer：梁家健
        /// Create Date：2017-03-20
        public DataTable ReturnPLPlanYMSetList()
        {
            try
            {
                var sql = $@"SELECT  *
FROM    ngoods.ngoods_PL_PlanYMSet
WHERE   ExtrSource = '{UserInfo.UserExtrSource}'
        AND CompanyID = '{UserInfo.UserCompanyId}'
ORDER BY yearv DESC ,
        monthv DESC ";
                var cmd = Helper.GetSqlStringCommand(sql);
                return Helper.ExecuteDataTable(cmd);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// Writer：梁家健
        /// Create Date：2017-03-20
        [JsonType]
        [MustLogin]
        [Description("修改企划设置")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult ModifyPLPlanYMSet(PLPlanYMSetModel.NeceModel param)
        {
            try
            {
                if (param == null) return Error("参数对象为空");
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var dt = ReturnPLPlanYMSetList();
                var list = ModelConvertHelper<PLPlanYMSetModel.NeceModel>.ConvertToModel(dt);
                if (list.Any(d => d.Yearv == param.Yearv && d.Monthv == param.Monthv))
                {
                    return UpdatePLPlanYMSet(param);
                }
                else
                {
                    return CreatPLPlanYMSet(param);
                }
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// Writer：梁家健
        /// Create Date：2017-03-20
        //[JsonType] 
        //[MustLogin]
        //[Description("修改企划设置")]
        //[ReturnType(typeof(int), "0-成功")]
        public ApiResult UpdatePLPlanYMSet(PLPlanYMSetModel.NeceModel param)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var sql = $@"UPDATE  ngoods.ngoods_PL_PlanYMSet
SET     Finished = {{0}} ,
        Executint = {{1}}
WHERE   Yearv = {{2}}
        AND Monthv = {{3}}
        AND ExtrSource = '{UserInfo.UserExtrSource}'
        AND CompanyID = '{UserInfo.UserCompanyId}'";
                if (param == null) return Error("参数对象为空");
                if (param.Finished == 1) return Error("该企划设置已经完成");
                var dt = ReturnPLPlanYMSetList();
                var list = ModelConvertHelper<PLPlanYMSetModel.NeceModel>.ConvertToModel(dt);
                var cmdList = new List<CommandInfo>();
                foreach (var item in list)
                {
                    if (!(item.Yearv == param.Yearv && item.Monthv == param.Monthv))
                    {
                        var cmd = new CommandInfo()
                        {
                            CommandText =
                                    string.Format(sql, item.Finished, 0L, item.Yearv, item.Monthv)
                        };
                        cmdList.Add(cmd);
                    }
                }
                var cmdUpdate = new CommandInfo()
                {
                    CommandText =
                        string.Format(sql, param.Finished, param.Executint, param.Yearv, param.Monthv)
                };
                cmdList.Add(cmdUpdate);
                Helper.ExecuteSqlTran(cmdList);
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// Writer：梁家健
        /// Create Date：2017-03-20
        ///// Modify Date:2017-03-21 检测年月是否存在，增加开始时间，操作者字段值
        //[JsonType]
        //[MustLogin]
        //[Description("创建企划设置")]
        //[ReturnType(typeof(int), "0-成功")]
        public ApiResult CreatPLPlanYMSet(PLPlanYMSetModel.NeceModel param)
        {
            try
            {
                if (string.IsNullOrEmpty(UserInfo.UserCompanyId))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(UserInfo.UserExtrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var sql = $@"INSERT  INTO ngoods.ngoods_PL_PlanYMSet
        ( CompanyID ,
          Yearv ,
          Monthv ,
          BeginDate ,
          Finished ,
          Executint ,
          Operator ,
          ExtrSource
        )
VALUES  ( '{UserInfo.UserCompanyId}' ,
          {{0}} ,
          {{1}} ,
          '{{2}}' ,
          {{3}} ,
          {{4}} ,
          '{{5}}' ,
          '{UserInfo.UserExtrSource}'
        )";
                if (param == null) return Error("参数对象为空");
                var plan = ReturnPLPlanYMSet();
                //var queryCmd = Helper.GetSqlStringCommand($"select Count(1) from goods.goods_PL_PlanYMSet where Yearv={param.Yearv} and Monthv={param.Monthv}");
                //var Num= Helper.ExecuteScalar(queryCmd);
                //if (Convert.ToInt16(Num) > 0) return Error($"企划 [{param.Yearv}-{param.Monthv}] 已存在");
                if (plan != null && param.Executint == 1) return Error("已存在正在执行的企划设置");
                var cmdList = new List<CommandInfo>()
                {
                    new CommandInfo()
                    {
                        CommandText =
                            string.Format(sql, param.Yearv, param.Monthv,DateTime.Now, param.Finished, param.Executint,param.Operator)
                    }
                };
                Helper.ExecuteSqlTran(cmdList);
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// Writer：梁家健
        /// Create Date：2017-03-23
        [JsonType]
        [MustLogin]
        [Description("修改企划设置")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult UpdatePLPlanYMSetList(PLPlanYMSetModel.NeceModel param)
        {
            try
            {
                var sql = $@"UPDATE  ngoods.ngoods_PL_PlanYMSet
SET     Finished = {{0}} ,
        Executint = {{1}}
WHERE   Yearv = {{2}}
        AND Monthv = {{3}}
        AND ExtrSource = '{UserInfo.UserExtrSource}'
        AND CompanyID = '{UserInfo.UserCompanyId}'";
                var dt = ReturnPLPlanYMSetList();
                var list = ModelConvertHelper<PLPlanYMSetModel.NeceModel>.ConvertToModel(dt);
                var cmdList = new List<CommandInfo>();
                if (param.Finished == 0) return Error("该企划设置还未完成");
                foreach (var item in list)
                {
                    if (!(item.Yearv == param.Yearv && item.Monthv == param.Monthv))
                    {
                        var cmd = new CommandInfo()
                        {
                            CommandText =
                                    string.Format(sql, item.Finished, 0L, item.Yearv, item.Monthv)
                        };
                        cmdList.Add(cmd);
                    }
                }
                var cmdUpdate = new CommandInfo()
                {
                    CommandText = string.Format(sql, 0L, 1L, param.Yearv, param.Monthv)
                };
                cmdList.Add(cmdUpdate);
                Helper.ExecuteSqlTran(cmdList);
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        /// <summary>
        /// 返回企划设置信息
        /// </summary>
        /// <returns></returns>
        /// writer:梁家健
        /// Create Date：2017-03-20
        public PLPlanYMSetModel.ListModel ReturnPLPlanYMSet()
        {
            try
            {
                var sql = $@"SELECT  *
FROM    ngoods.ngoods_PL_PlanYMSet pset
        INNER JOIN ( SELECT *
                     FROM   ngoods.ngoods_PL_Bas_SeasonMonth
                     WHERE  ExtrSource = '{UserInfo.UserExtrSource}'
                            AND CompanyID = '{UserInfo.UserCompanyId}'
                   ) sm ON pset.Monthv = sm.Monthv
                           AND pset.ExtrSource = sm.ExtrSource
                           AND pset.CompanyID = sm.CompanyID
WHERE   pset.Executint = 1
        AND pset.ExtrSource = '{UserInfo.UserExtrSource}'
        AND pset.CompanyID = '{UserInfo.UserCompanyId}'";
                var cmd = Helper.GetSqlStringCommand(sql);
                var ds = Helper.ExecuteDataSet(cmd);
                return ModelConvertHelper<PLPlanYMSetModel.ListModel>.DataSetToEntity(ds);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}
